<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 */
namespace app\api\model;

use common\Auth;
use app\api\model\Model;
use Mscore\Core\Lang;
use Mscore\Core\Util\Util;

class Login extends Model{

    private $token;  //登陆token
    private $usertable = 'user_account';
    private $error;
    private $success;
    private $header; //header值
    private $runmode;

    public function __construct()  
    {    
        // $this->runmode = config("app.runmode");
        $this->cross = config("app.cross");
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:'default';
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }
    
    /**
     *  用户登陆
     * @param $token
    */
    public function userAuth($username='',$passwd='', $ip='127.0.0.1'){
        $info = (new Auth)->userAuth($username,$passwd,$ip);
        return $info;
    }

    /**
     *  用户检测
     * @param $token
    */
    public function isAuth(){
        header('Content-Type:application/json; charset=utf-8');
        if($this->cross['crossdomain']){
            foreach ($this->cross['crossinfo'] as $key => $value) {
                header($value);
            }
        }
        if (!isset($this->header['authorization'])&&empty($this->header['authorization'])) {
            $this->error=Lang::get('Tokenempty');
            exit(json_encode($this->error));
        }
        $this->token=$this->header['authorization'];
        $user = (new Auth)->isAuth($this->token);
        switch ($user) {
            case $user['code']==200:
                unset($user['data']['token'],$user['data']['info']['role'],$user['data']['info']['ranges']);
                $this->success=$user['data']['info'];
                return $this->success;
                break;
            //数据不存在退出
            default:
                $this->error=Lang::get('Tokenexp');
                exit(json_encode($this->error));  
                break;
        }
    }

    /**
     * 注册
     */
    public function register($params)
    {
        $showpwd=['password'=>'','paypwd'=>''];
        $username = urlencode($params['username']);
        $password = Util::passwordHash($params['password']);
        $showpwd['password'] = Util::phpEncode($params['password']);
        //排除用户名重复
        $is_user = Model::name($this->usertable)->where('username="'.$username.'"')->count('aid');
        if ($is_user) {
            $this->error = Lang::get('Nameextends');
            return $this->error;
        }

        //排除电话重复
        if(isset($params['mobile'])&&!empty($params['mobile'])){
            $is_user = Model::name($this->usertable)->where('mobile="'.$params['mobile'].'"')->count('aid');
            if ($is_user) {
                $this->error = Lang::get('Mobileextends');
                return $this->error;
            }
        }

        //排除email重复
        if(isset($params['email'])&&!empty($params['email'])){
            $is_user = Model::name($this->usertable)->where('email="'.$params['email'].'"')->count('aid');
            if ($is_user) {
                $this->error = Lang::get('Emailextends');
                return $this->error;
            }
        }

        if(isset($params['paypwd'])&&!empty($params['paypwd'])){
            $paypwd = Util::passwordHash($params['paypwd']);
            $showpwd['paypwd'] = Util::phpEncode($params['paypwd']);
        }else{
            $paypwd = '';
            $showpwd['paypwd'] = '';
        }
        
        $data = [
            'username' => $username,
            'password' => $password,
            'paypwd' => $paypwd,
            'showpwd'=>json_encode($showpwd,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'mobile' => isset($params['mobile']) ? $params['mobile'] : '',
            'email' => isset($params['email']) ? $params['email'] : '',
            'grade'=>'member',
            'pid'=>isset($params['pid'])?$params['pid']:0,
            'ranges'=>0,
            'status' => 1,
            'roletype'=>2,
            'chat'=>isset($params['chat'])?$params['chat']:'',
            'chattype'=>isset($params['chattype'])?$params['chattype']:0,
            'usercode' => getRandStr(6)
        ];

        $res =  Model::name($this->usertable)->insert($data);
        switch (true) {
            case !empty($res):
                $this->success = Lang::get('Regsuccessful');
                return $this->success;
                break;
            default:
                $this->error = Lang::get('Regerror');
                return $this->error;
                break;
        }
    }
    
    /**
     * 更新密码
     * @param array $updatepwd 
     * @param array $where 
    */ 
    public function updatepwd($params=[]){
        $password = Util::passwordHash($params['newpassword']);
        $data = [
            'password' => $password
        ];
        Model::name($this->usertable)->where(' email="' . $params['email'].'" or mobile="' . $params['mobile'].'"')->update($data);
        return $this->success;
    }

    /**
     *  获取token
     * @param $token
     */
    public function getAccID($where=''){
        return Model::name($this->usertable)->where($where)->value('aid');
    }

    /**
     *  获取token
     * @param $token
     */
    public function getToken(){
        if (!isset($this->header['authorization'])) {
            $this->error=Lang::get('Tokenexp');
            return $this->error;
        }
        $this->token=$this->header['authorization'];
        $data = (new Auth)->getToken($this->token);
        $this->success['data']=$data;
        return $this->success;
    }
    
    /**
     * 退出登录
     * @param array $module 
     * @param array $user 
    */
    public function logout($ip=''){
        $this->token=$this->header['authorization'];
        return (new Auth)->logout($this->token,$ip);
    }      

}